﻿using System;
using Newtonsoft.Json;

namespace Flagwind.Externals.Json.Converters
{
	public class Int64Converter : JsonConverter
	{
		#region 重写方法

		public override bool CanConvert(Type objectType)
		{
			var type = Type.GetTypeFromHandle(objectType.TypeHandle);

			return type == typeof(long) || type == typeof(long?);
		}

		public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
		{
			if(value == null)
				writer.WriteNull();

			if(value is long)
				writer.WriteValue(value.ToString());
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
		{
			if(reader.TokenType == JsonToken.Null)
				return Flagwind.Common.Convert.ConvertValue<long?>(reader.Value, () => null);

			return Flagwind.Common.Convert.ConvertValue<long>(reader.Value, 0);
		}

		#endregion
	}
}
